<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="../static/images/local/校标.jpg" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>所有用户信息</title>
        <link rel="stylesheet" href="../static/layui/css/layui.css">
    <style>
        body{margin: 10px;}
        .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    </style>

</head>
<body>
<!--弹出层表格-->
<div style=" display: none" id="add_edit">
    <form class="layui-form" >
        <div class="layui-form-item">
            <label class="layui-form-label">手机号码</label>
            <div class="layui-input-inline">
                <label for="phone"></label><input type="number" id="phone" name="phone" required lay-verify="required" placeholder="您的手机号码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-inline">
                <label for="password"></label><input type="text" id="password" name="password" required lay-verify="required" placeholder="您的密码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-inline">
                <label for="sex"></label><select name="8afr" id="sex" required lay-verify="required" lay-search>
                <option value=""></option>
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
                <label for="username"></label><input type="text" id="username" name="username" required lay-verify="required" placeholder="您的用户名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-inline">
                <label for="email"></label><input type="email" id="email" name="u6dgp" required lay-verify="required" placeholder="您的邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>

    </form>
</div>

<table class="layui-hide" id="demo" lay-filter="test" ></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">查看选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="edit">编辑</button>
        <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
    </div>
</script>
<script type="text/html" id="barDemo" >
    <a class="layui-btn layui-btn-xs" lay-event="save">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>



<script src="../static/layui/layui.js" ></script>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
    const suffix=localStorage.getItem("suffix");
    const prefix=localStorage.getItem("prefix");
    if(sessionStorage.getItem("root")!=="1")
    {window.alert("请先登录!");window.location.href=prefix+"/logIn"+suffix;}
    layui.config({
        version: '1632428048355' //为了更新 js 缓存，可忽略
    });
    const baseUrl=localStorage.getItem("baseUrl");
    //加载模块
    layui.use(function(){ //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
        //得到各种内置组件
        const layer = layui.layer //弹层
            , laypage = layui.laypage //分页
            , table = layui.table //表格
            , element = layui.element; //元素操作
        //向世界问个好
        layer.msg('你好，亲爱的管理员');

        //监听Tab切换
        element.on('tab(demo)', function(data){
            layer.tips('切换了 '+ data.index +'：'+ this.innerHTML, this, {
                tips: 1
            });
        });
        //执行一个 table 实例
        table.render({
             height:620
            ,width:1500
            ,elem: '#demo'
            ,url: baseUrl+'/admin/getAllUser' //数据接口
            // ,url: '/admin/getAllUser-page=1&limit=2.js' //数据接口
            ,parseData: function(res){ //res 即为原始返回的数据
                let result;
                if (this.page.curr) {
                    result= res.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                } //前端对数据切割分页
                else {
                    result = res.slice(0, this.limit);
                }
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.length, //解析数据长度
                    "data": result //解析数据列表
                };
            }
            ,title: '用户表'
            ,page: true //开启分页
            ,limit:10
            ,limits:[5,10,15,20]
            ,toolbar: '#toolbarDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            ,totalRow: false //开启合计行
            ,cols: [
                [ //表头
                    {type: 'checkbox', fixed: 'left'}
                    ,{field: 'userPhone', title: '手机号码', width:'20%',align: 'center', sort: true, fixed: 'left'}
                    ,{field: 'userName', title: '用户名', width:'20%',align: 'center',sort: true}
                    ,{field: 'userPassword', title: '用户密码', width: '15%', align: 'center',sort: true,edit:'text'}
                    ,{field: 'sex', title: '性别', width:'5%', sort: true,align: 'center',edit:'text'}
                    ,{field: 'userEmail', title: '邮箱', width: '20%', sort: true,align: 'center', edit:'text'}
                    ,{fixed: 'right', width: '16.8%', align:'center', toolbar: '#barDemo'}
                ]
            ]
        });

        //监听头工具栏事件
        table.on('toolbar(test)', function(obj){
            const checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch(obj.event){
                case 'add': {
                    layer.open({
                        area: ['500px', '500px'],
                        type:1,
                        maxmin:true,
                        title:"新增",
                        content:$('#add_edit'),
                        end:function (res) {
                            $("#add_edit").css("display",'none');
                        },
                        btn:['添加','取消'],
                        yes:function(index, layero){
                            // 取出输入框的内容
                            const phone = $('#phone').val();
                            const password = $('#password').val();
                            const sex = $('#sex').val();
                            const email = $('#email').val();
                            const username = $('#username').val();
                            // 如果有一项数据未填，则弹出提示框
                                const user={
                                    userPhone: phone,
                                    userName: username,
                                    userPassword: password,
                                    sex: sex,
                                    userEmail: email,
                                    userRoot: 0,
                                }
                               if(check1(user)) {
                                //向服务端发送新增指令
                                // '/book/addbook'
                                $.ajax(
                                    {
                                        url: baseUrl+"/user/signIn",
                                        dataType: "json",
                                        type: "post",
                                        headers: {
                                            'Content-Type': 'application/json;charset=utf-8'
                                        },
                                        data: JSON.stringify(user),
                                        success: function (res) {
                                            console.log(res)
                                            if (res===1) {
                                                layer.msg("添加成功");
                                                table.reload('demo');
                                            }
                                            else layer.alert("账号已注册!");
                                        },
                                        error: function () {
                                            alert("服务器内部请求错误!");
                                        }
                                    });
                                layer.close(index)
                            }
                            return false
                        }
                    })
                }
                    break;
                case 'update':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else if(data.length > 1){
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                    }
                    break;
                case 'delete':
                    if(data.length === 0){
                        layer.msg('请选择一行');
                    } else {
                        layer.msg('删除');
                    }
                    break;
            }
        });
        //监听行工具事件
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            const data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if(layEvent === 'save'&&check1(data)){
                $.ajax({
                    url: baseUrl+"/admin/update_user",
                    dataType: "json",
                    type: "post",
                    headers : {
                        'Content-Type' : 'application/json;charset=utf-8'
                    },
                    data: JSON.stringify(data),
                    success:function (res) {
                        console.log(res)
                        if (res) {layer.msg("保存成功!");}
                        else layer.alert("保存失败!");
                    },
                    error: function ()
                    {
                        alert("服务器内部请求错误!");
                    }
                })
            } else if(layEvent === 'delete'){
                layer.confirm('真的删除行么', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    $.ajax({
                        url: baseUrl+"/admin/delete_user",
                        dataType: "json",
                        type: "post",
                        headers : {
                            'Content-Type' : 'application/json;charset=utf-8'
                        },
                        data: JSON.stringify(data),
                        success:function (res) {
                            console.log(res)
                            if (res) {layer.msg("删除成功!");}
                            else layer.alert("删除失败!");
                        },
                        error: function ()
                        {
                            alert("服务器内部请求错误!");
                        }
                    })
                })

            }});

        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            ,count: 1000 //数据总数
            ,limit: 1//每页显示的数据条数
            ,skin: '#1E9FFF' //自定义选中色值
            //,layout: ['prev', 'page', 'next', 'count', 'limit', 'refresh', 'skip'] //自定义排版
            ,jump: function(obj, first){
                if(!first){
                    layer.msg('第'+ obj.curr +'页', {offset: 'b'});
                }
            }
        });

    });
    function check1(data) {
        const username =data.userName;
        const password = data.userPassword;
        const email=data.userEmail;
        const phone=data.userPhone;
        if ($.trim(phone) === '' || $.trim(phone).length<=0){
            console.log(phone);
            layer.alert("手机号不能为空");
            return false;
        }
        if (phone.length>11||phone.length<5){
            console.log(phone);
            layer.alert("手机号格式错误");
            return false;
        }
        if ($.trim(username)===""){
            layer.alert("请输入用户名");
            return false;
        }
        if (username.length>=20){
            layer.alert("用户名格式错误");
            return false;
        }
        if ($.trim(password) === '' || $.trim(password).length<=0){
            layer.alert("密码不能为空");
            return false;
        }
        if (password.length>=20||/.*[\u4e00-\u9fa5]+.*$/.test(password)){
            layer.alert("密码格式错误");
            return false;
        }
        if(!(/^[\w_.]+@[\w-]+(\.[\w-]+)*\.[0-9a-zA-Z0]{2,6}$/).test(email)&&$.trim(email)!=="")
        {
            layer.alert("邮箱格式错误!");
            return false;
        }
        return true;
    }
</script>
</body>
</html>
